<!--
 * @Author: 宋绍华
 * @Date: 2024-11-12 14:58:02
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-01-17 11:18:06
 * @FilePath: \scientific_research_manager_web\src\views\project\components\MyProject\ProjectMemberHasChange.vue
 * @Description: 项目成员
-->
<template>
  <div px-20px>
    <div class="mb-16px flex justify-end">
      <el-button :class="[props.mode === 'add' ? 'mt-10px' : 'mt-[-32px]']" v-if="props.mode !== 'view'" type="primary"
        @click="addMember">添加</el-button>
    </div>
    <div>
      <el-table border :data="tableData" style="width: 100%">
        <el-table-column label="署名顺序" width="100px">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="170px">
          <template #default="scope">
            <template v-if="mode !== 'view'">
              <el-input v-if="scope.$index === 0" :disabled="scope.$index === 0" :maxlength="50" style="width: 150px"
                v-model="scope.row.name" placeholder="请输入" />
              <el-select
                @change="(v) => onChange(v, scope.row, true, scope.$index)" remote reserve-keyword style="width: 150px"
                v-else v-model="scope.row.name" filterable allow-create default-first-option
                :loading="getAllPersonListLoading" :remote-method="remoteMethod" placeholder="请输入">
                <el-option v-for="item in memberList" :key="item.name" :label="`${item.name}（${item.code || '-'}）`"
                  :value="item.name" />
              </el-select>
            </template>
            <span v-else>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sex" label="性别">
          <template #default="scope">
            <el-select v-if="mode !== 'view'" style="width: 136px" v-model="scope.row.sex" placeholder="请选择">
              <el-option :value="1" label="男" />
              <el-option :value="2" label="女" />
            </el-select>
            <span v-else>{{ scope.row.sex === 1 ? '男' : '女' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="birth" label="出生年月">
          <template #default="scope">
            <el-date-picker :disabled-date="disabledDate" v-if="mode !== 'view'" style="width: 136px"
              v-model="scope.row.birth" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="选择日期" />
            <span v-else>{{ formateDate(scope.row.birth).format('YYYY-MM-DD') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="职称">
          <template #default="scope">
            <el-select v-if="mode !== 'view'" style="width: 136px" v-model="scope.row.title" placeholder="请选择">
              <el-option v-for="dict of getDicListById(13, props.dictList)" :key="dict.dataId" :label="dict.dataName"
                :value="dict.dataId" />
            </el-select>
            <span v-else>{{ scope.row.titleName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="researchDirection" label="研究方向">
          <template #default="scope">
            <el-input :maxlength="2000" v-if="mode !== 'view'" style="width: 136px"
              v-model="scope.row.researchDirection" placeholder="请输入" />
            <span v-else>{{ scope.row.researchDirection }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="educational" label="学历">
          <template #default="scope">
            <el-select v-if="mode !== 'view'" style="width: 136px" v-model="scope.row.educational" placeholder="请选择">
              <el-option v-for="dict of getDicListById(19, props.dictList)" :key="dict.dataId" :label="dict.dataName"
                :value="dict.dataId" />
            </el-select>
            <span v-else>{{ scope.row.educationalName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="degree" label="学位">
          <template #default="scope">
            <el-select v-if="mode !== 'view'" style="width: 136px" v-model="scope.row.degree" placeholder="请选择">
              <el-option v-for="dict of getDicListById(20, props.dictList)" :key="dict.dataId" :label="dict.dataName"
                :value="dict.dataId" />
            </el-select>
            <span v-else>{{ scope.row.degreeName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="jobResponsibilities" label="职责分工">
          <template #default="scope">
            <el-input v-if="mode !== 'view'" style="width: 136px" :maxlength="50"
              v-model="scope.row.jobResponsibilities" placeholder="请输入" />
            <span v-else>{{ scope.row.jobResponsibilities }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="workUint" label="工作单位">
          <template #default="scope">
            <el-input v-if="mode !== 'view'" style="width: 136px" :maxlength="50" v-model="scope.row.workUint"
              placeholder="请输入" />
            <span v-else>{{ scope.row.workUint }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" v-if="props.mode !== 'view'">
          <template #default="scope">
            <el-button type="danger" v-if="scope.$index !== 0" link @click="deleteMember(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { BaseSuccessRespDTO, DictionaryListRespVO, MemberDTO } from '@/api/project/types';
import { getDicListById } from '../../utils';
import { getProjectMemberApi, projectMemberCreateApi } from '@/api/project';
import formateDate from '@/utils/formateDate';
import { getAllPersonListApi } from '@/api/resultsManagement';
import { AccountListVO } from '@/types/resultsManagement';

const props = defineProps({
  dictList: {
    type: Array as PropType<DictionaryListRespVO[]>,
    default: () => []
  },
  projectId: {
    type: String,
    default: ''
  },
  mode: {
    type: String as PropType<'add' | 'edit' | 'view'>,
    default: 'add'
  },
  managerName: { // 负责人名字
    type: String,
    default: ''
  },
  data: {
    type: Array,
    default: () => []
  },
})

const tempData = {
  jobResponsibilities: undefined, // 职责分工
  educational: undefined, // 学历
  /**
    * 学位
    */
  degree: undefined,
  /**
   * 成员出生年月
   */
  birth: undefined,
  /**
   * 成员名称
   */
  name: undefined,
  /**
   * 成员性别;1男 2女
   */
  sex: undefined,
  /**
   * 成员职称
   */
  title: undefined,
  /**
   * 工作单位
   */
  workUint: undefined,
  researchDirection: undefined, // 研究方向
}
const tableData = ref<MemberDTO[]>([])
const memberList = ref<AccountListVO[]>([]) // 人员信息列表
// 获取详情
const { runAsync: getProjectDetails } = useRequest(getProjectMemberApi, {
  manual: true,
  onSuccess: (res) => {
    tableData.value = res
  }
})

// 添加成员
const addMember = async () => {
  tableData.value.push({ ...tempData })
  // 如果第一条数据，名字是不能更改的
  if (tableData.value?.length === 1) {
    tableData.value[0].name = props.managerName
    await getAllPersonList({ name: props.managerName })
    onChange(props.managerName, tableData.value[0], false)
    memberList.value.length = 0
  }
}

/* 查询 人员信息 列表 */
const { runAsync: getAllPersonList, loading: getAllPersonListLoading } = useRequest(getAllPersonListApi, {
  // false 为自动执行
  manual: true,
  // 请求成功
  onSuccess: (response: AccountListVO[]) => {
    if (response) {
      memberList.value = response
      return response
    }
  }
})

onMounted(() => {
  if(props.data?.length){
    tableData.value = props.data
  }
})
watch(
  () => [props.mode, props.projectId],
  async () => {
    if(props.data?.length){
      return
    } 
    if (props.mode !== 'add' || props.projectId) {
      await getProjectDetails({ projectId: props.projectId })
    }

    // 新增
    if (props.mode === 'add' && tableData.value.length === 0) {
      setTimeout(() => {
        addMember()
      }, 400)
    }
    if (!tableData.value.length || !props.managerName) return
    tableData.value[0].name = props.managerName
  },
  {
    immediate: true
  }
)

// 删除成员
const deleteMember = (index: number) => {
  tableData.value.splice(index, 1)
}

const validate = () => {
  return tableData.value.every(i => {
    const isEmpty = Object.keys(i).every(key => {
      if ((i[key] === undefined || i[key] === '') && tempData.hasOwnProperty(key)) {
        return false
      }
      return true
    })
    return isEmpty
  })
}

// 禁用日期
const disabledDate = (time) => {
  const date = new Date(time)
  return date.getTime() >= Date.now() - 8.64e7
}

// 远程搜索
const remoteMethod = (query: string) => {
  if (!query) return []
  return getAllPersonList({ name: query })
}

// 清除当前行
const clearCurRow = (idx: number = 0) => {
  const curRow = tableData.value[idx]
  if (curRow) {
    curRow.title = undefined
    curRow.sex = undefined
    curRow.educational = ''
    curRow.birth = undefined
    curRow.degree = ''
    curRow.workUint = ''
    curRow.researchDirection = ''
    curRow.researchDirection = ''
    curRow.jobResponsibilities = ''
  }
}

// 名称change 事件
function onChange(val: string, row, needCode = true, idx?: number) {
  // 找到当前输入的值
  const curItem = memberList.value.find(item => item.name === val)

  if (curItem) {
    // 清楚当前行的值
    clearCurRow(idx)
    const { titleId, inside, name, code, sex, direction, educationId, birthday, academicId } = curItem
    row.title = titleId //成员职称
    row.sex = sex // 性别
    row.researchDirection = direction // 研究方向
    row.educational = educationId // 学历
    row.birth = birthday  // 出生年月
    row.degree = academicId // 学位
    row.name = needCode ? `${name}(${code || '-'})` : name
    row.workUint = inside ? '南昌交通学院' : ''  // 工作单位
    row.baseName = name // 基本名称，用于后续比较判断
  } else {
    clearCurRow(idx)
  }
  memberList.value.length = 0
}

// 创建or更新成员
const { runAsync: projectMemberCreate } = useRequest(projectMemberCreateApi, {
  manual: true,
  onSuccess: (res: BaseSuccessRespDTO, params) => {
    if (res.isSuccess && (params[0].isSave || params[0].isTemp)) {
      ElMessage({
        message: '操作成功',
        type: 'success',
      })
    }

    return res.isSuccess
  }
})

// 创建项目
const createProjectMember = async (isTemp: boolean = false, isSave: boolean = false) => {
  // 暂存
  if (isTemp) {
    projectMemberCreate({ memberDTOList: tableData.value, isTemp, projectId: props.projectId })
    return true
  }

  const res = await validate()

  if (!res) {
    ElMessage.error('请完善内容')
    return false
  } else {
    try {
      return await projectMemberCreate({ memberDTOList: tableData.value, isTemp, projectId: props.projectId, isSave })
    } catch (error) {
      console.log(error, 'error');
    }
  }
}

defineExpose({
  createProjectMember,
  memberDTOList: tableData,
  validate
})
</script>
